package com.boot.security;

import cn.hutool.json.JSONUtil;
import com.boot.api.ApiCode;
import com.boot.api.ApiResult;
import com.boot.app.base.dto.UserDetailsImpl;
import com.boot.app.base.vo.UserInfo;
import com.boot.util.JwtTokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class IAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public IAuthenticationSuccessHandler(JwtTokenUtil jwtTokenUtil){ this.jwtTokenUtil = jwtTokenUtil; }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails.getUsername());
        response.setContentType("text/json;charset=UTF8");
        response.getWriter().write(JSONUtil.toJsonStr(ApiResult.success(ApiCode.SUCCESS.getMsg(), token)));
    }
}
